/**
 *
 */
package com.abel.quiz.common.widget;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @author abel.lin
 * @date_time 2016-10-25 上午10:10:31
 * @description
 */
public class HttpClientAPI {
    private static Logger log = LoggerFactory.getLogger(HttpClientAPI.class);

    private static String jsonType = "json";
    private static String formType = "form";
    private static String xmlType = "xml";

    public static String postJson(String requestPath, String params, String encoding) throws Exception {
        return post(requestPath, params, jsonType, encoding);
    }

    public static String postForm(String requestPath, Map<String, Object> params, String encoding) throws Exception {
        return post(requestPath, constructURLString(params, encoding), formType, encoding);
    }

    public static String postXml(String requestPath, String params, String encoding) throws Exception {
        return post(requestPath, params, xmlType, encoding);
    }

    public static String post(String requestPath, String params, String paramsType, String encoding) throws Exception {
        return sendRequest(requestPath, params, paramsType, encoding,"POST");
    }

    public static String get(String requestPath, String params) throws Exception {
        return sendRequest(requestPath, params, formType, "UTF-8","GET");
    }
    private static String sendRequest(String requestPath, String params, String paramsType, String encoding,String requestType) throws Exception {
        String body = "";


        byte[] data = params.getBytes(encoding);
        URL url = new URL(requestPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(requestType.toUpperCase());
        conn.setDoOutput(true);

        String contentType = "application/x-www-form-urlencoded; charset=" + encoding;  //表单数据
        if (jsonType.equals(paramsType)) {
            contentType = "application/x-javascript; charset=" + encoding;   //json数据
        } else if (xmlType.equals(paramsType)) {
            contentType = "application/x-javascript text/xml; charset=" + encoding;  //xml数据
        }

        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
        conn.setConnectTimeout(5 * 1000);
        OutputStream outStream = conn.getOutputStream();
        outStream.write(data);
        outStream.flush();
        outStream.close();

        log.info("request code=" + conn.getResponseCode()); //响应代码 200表示成功
        if (conn.getResponseCode() == 200) {
            InputStream inStream = conn.getInputStream();
            body = convertStreamToString(inStream, encoding);
        }
        log.info("body=" + body);

        return body;
    }

    public static String convertStreamToString(InputStream is, String encoding) {
        try {
            InputStreamReader input = new InputStreamReader(is, encoding);
            final int CHARS_PER_PAGE = 5000; // counting spaces
            final char[] buffer = new char[CHARS_PER_PAGE];
            StringBuilder output = new StringBuilder(CHARS_PER_PAGE);
            try {
                for (int read = input.read(buffer, 0, buffer.length); read != -1; read = input
                        .read(buffer, 0, buffer.length)) {
                    output.append(buffer, 0, read);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            return output.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";

    }

    private static String constructURLString(Map<String, Object> parameters) {
        return constructURLString(parameters, "UTF-8");
    }

    private static String constructURLString(Map<String, Object> parameters, String encoding) {
        StringBuffer url = new StringBuffer();

        boolean first = true;

        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            try {
                // type checking, we can get nulls in here
                if ((entry.getValue() == null) || (entry.getKey() == null)) {
                    continue;
                }
                if (entry.getValue().toString().trim().length() == 0) {
                    continue;
                }

                if (first) {
                    first = false;
                } else {
                    url.append("&");
                }
                url.append(URLEncoder.encode(entry.getKey(), encoding) + "="
                        + URLEncoder.encode(entry.getValue().toString(), encoding));
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
                // No Fixing this, really
                throw new Error("Unsupported Encoding Exception", ex);
            }
        }

        return url.toString();
    }

}
